#!/bin/sh

# dependencies:
# mount grep readlink hdparm whoami

[ "$(whoami)" != "root" ] && echo "Sorry, you must have root privileges to run this script" && exit 1

# These _must_ be defined outside the script
[ -z "$node" ] && echo "You must export \$node variable!" && exit 1
[ -z "$hdparm_device" ] && echo "You must export \$hdparm_device variable!" && exit 1

basepath="/sys/bus/usb"
bind_file="$basepath/drivers/usb/bind"
unbind_file="$basepath/drivers/usb/unbind"
autosuspend_file="$basepath/devices/$node/power/autosuspend_delay_ms"
control_file="$basepath/devices/$node/power/control"
restore_autosuspend="${restore_autosuspend:-2000}" # default value
restore_control="${restore_control:-on}" # default value

case "$1" in
    off)
        # Must not be mounted
        if [ -r "$hdparm_device" ]; then
            mount | grep "^$(readlink -f "$hdparm_device")" && echo "Must not be mounted!" && exit 1
            # First, send it to sleep.
            /usr/bin/hdparm -Y "$hdparm_device" || exit 1 # systemd unit will retry on fail
        fi
        # echoing states
        echo "Before:"
        printf "%s: %s\n" "$autosuspend_file" "$(cat "$autosuspend_file")"
        printf "%s: %s\n" "$control_file" "$(cat "$control_file")"
        # stackoverflow.com/a/12675749
        echo "0" > "$autosuspend_file" || exit 1
        echo "auto" > "$control_file" || exit 1
        echo "After:"
        printf "%s: %s\n" "$autosuspend_file" "$(cat "$autosuspend_file")"
        printf "%s: %s\n" "$control_file" "$(cat "$control_file")"
        # stackoverflow.com/a/18098075
        echo "$node" > "$unbind_file" && echo "Unbinding $node succeeded." || echo "Unbinding $node failed, but that's not necessarily a problem. Please investigate."
        exit 0
    ;;
    on)
        # Waking it up in reverse order
        echo "$node" > "$bind_file" && echo "Binding $node succeeded" || echo "Binding $node failed, but that's not necessarily a problem. Please investigate."
        # echoing states
        echo "Before:"
        printf "%s: %s\n" "$autosuspend_file" "$(cat "$autosuspend_file")"
        printf "%s: %s\n" "$control_file" "$(cat "$control_file")"
        # Action
        echo "$restore_autosuspend" > "$autosuspend_file" || exit 1
        echo "$restore_control" > "$control_file" || exit 1
        ###############################################
        echo "After:"
        printf "%s: %s\n" "$autosuspend_file" "$(cat "$autosuspend_file")"
        printf "%s: %s\n" "$control_file" "$(cat "$control_file")"
        # There's no need to wake the device up with hdparm; it will do so when accessed, albeit with a delay.
        exit 0
    ;;
    *)
        echo "Wrong argument $1"; exit 1
    ;;
esac >&2
